function EEG = cvc_cartoon(EEG)
% CVC_CARTOON
%
%  Synopsis
%  ========
%
%  EEG = cvc_cartoon(EEG)
%
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     June 2010
%
%  Purpose
%  =======
%
%  Switch to spherical "cartoon" locations.
%
%  Inputs
%  ======
%
%  EEG - EEGLAB dataset.
%
%  Outputs
%  =======
%
%  EEG - dataset with updated EEG.chanlocs structure.

LOCSMODE_DIGITIZER=0;
LOCSMODE_CARTOON=1;

if ~isfield(EEG.cvc,'locsmode')
  EEG.cvc.locsmode = LOCSMODE_DIGITIZER; % default is digitizer
end

if EEG.cvc.locsmode==LOCSMODE_CARTOON % already cartoon?
  return
end
%ELSE currently digitizer...

% save digitizer if not done before
if ~isfield(EEG.cvc,'digitizer')
  EEG.cvc.digitizer = EEG.chanlocs;
end

% read cartoon locs from file if necessary
if ~isfield(EEG.cvc,'cartoon') 
  [pp,nn,ee] = fileparts(which('cvc_cartoon'));
  cartoonroot = fullfile(pp,['cvc_cartoon256.sph']);
  eloc = readlocs(cartoonroot);
  idx = 1;
  % for some reason READLOCS doesn't get the labels, so fix...
  for letter = ['A','B','C','D','E','F','G','H'];
    for nummer = 1:32
      eloc(idx).labels = [letter num2str(nummer)];
      idx = idx+1;
    end
  end
  EEG.cvc.cartoon = eloc; % (*)
else 
  % we have them already (*)
  eloc = EEG.cvc.cartoon;
end

% match electrode names
huske = [];
for chan=1:EEG.nbchan
  I = strmatch(EEG.chanlocs(chan).labels, {eloc.labels}, 'exact');
  if isempty(I)
    I = nan;
  end
  huske = [huske;I];
end

% build 
for chan=1:length(huske)
  newchan = huske(chan);
  if ~isnan(newchan)
    % new matched chan
    newlocs(chan) = eloc(newchan);
  else
    % old non-matched chan
    newlocs(chan).labels = EEG.chanlocs(chan).labels;
  end
end
EEG.chanlocs = newlocs;

EEG = eeg_checkset(EEG);

% channel types
EEG=pop_chanedit(EEG, EEG.chaninfo,  'settype',{ find(~isnan(huske)), 'EEG'});
% head radius for dipfit
EEG=pop_chanedit(EEG, EEG.chaninfo,  'headrad',85);

% compensate for EEGLAB bug 872 which I patched eeglab2fieldtrip
if isfield(EEG.chaninfo,'nodatchans') && isempty(EEG.chaninfo.nodatchans)
  EEG.chaninfo = rmfield(EEG.chaninfo,'nodatchans');
end

EEG.cvc.locsmode = LOCSMODE_CARTOON;
  
